package org.custom.spring.boot.security.config.security;

import org.custom.spring.boot.security.entity.SystemUser;
import org.custom.spring.boot.security.mapper.SystemRoleMapper;
import org.custom.spring.boot.security.mapper.SystemUserMapper;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

import static org.cleaver.basic.constant.CleaverConstant.EMPTY;

/**
 * 用户身份校验服务接口
 *
 * @author LiKun
 * @date 2021/11/8 21:32
 */
@Service
public class SystemUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SystemRoleMapper systemRoleMapper;
    @Resource
    private SystemUserMapper systemUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 直接抛出 UsernameNotFoundException 会被 BadCredentialsException 覆盖掉
        SystemUser user = Optional.ofNullable(systemUserMapper.selectByUsername(username))
                .orElseThrow(() -> new InternalAuthenticationServiceException(EMPTY));

        return user.setAuthorities(systemRoleMapper.selectByUserId(user.getId()));
    }
}
